package com.haojiang.mh.remote.adapter

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.haojiang.mh.remote.bean.FragBean

class FragStateAdapter(fm: FragmentActivity, fragSubList: ArrayList<FragBean>) : FragmentStateAdapter(fm) {

//    private var viewList = ArrayList<ControlMenuItem>()
    private val dataHashCodeLIst = ArrayList<Long>()
    private val fragSubList = ArrayList<FragBean>()
//    private val fm = context.supportFragmentManager

    //    fun removeFragment(position: Int) {
//        items.removeAt(position)
//        notifyItemRangeChanged(position, items.size)
//        notifyDataSetChanged()
//    }
//    fun removeFragment() {
//        for (index in 0..dataList.size) {
//            dataList.removeAt(index)
//            notifyItemRangeChanged(index, dataList.size)
//        }
//        dataListHashCode.clear()
//        notifyDataSetChanged()
//    }
    init {
//        viewList.clear()
        this.fragSubList.clear()
        this.dataHashCodeLIst.clear()
        this.fragSubList.addAll(fragSubList)
        this.fragSubList.forEach {
            dataHashCodeLIst.add(it.code.hashCode().toLong())
        }
//        menuMap.forEach {
//            dataHashCodeLIst.add(it.key.hashCode().toLong())
//            viewList.add(it.value)
//        }
    }

//    fun getCurrenFragCode(fragCode: Int): Int {
//        for (i in 0 until viewList.size) {
//            if(viewList.get(i).code == fragCode) {
//                return i
//            }
//        }
//        return  0
//    }

//    @Synchronized
//    fun setData(list: List<ControlMenuItem>) {
//        if (list.size <= 0) return
//        dataList.clear()
//        dataHashCodeLIst.clear()
//        dataList.addAll(list)
//        dataList.forEach {
//            it.hashCode().toLong()
//            dataHashCodeLIst.add(it.hashCode().toLong())
//        }
//        notifyDataSetChanged()
//    }

//    private fun getFragment(code: Int): Fragment {
//        return this.fragSubList.get()
//        return FragSurfaceMananger.fragSurfaceMananger.getFragment(code)
//    }

    override fun getItemCount(): Int {
        return this.fragSubList.size
    }

    override fun createFragment(position: Int): Fragment {
//        fm.executePendingTransactions()
//        val fragment = getFragment(viewList.get(position).code)
//        fm.beginTransaction().remove(fragment)
        return fragSubList.get(position).frag
//        return getFragment(dataList.get(position).code)
    }

    override fun getItemId(position: Int): Long {
        return fragSubList[position].code.toLong()     // make sure notifyDataSetChanged() works
    }

    override fun containsItem(itemId: Long): Boolean {
        return dataHashCodeLIst.contains(itemId)
    }

}
